package controllers;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.CategoryModel;
import models.UserModel;

import data.CategoryData;
import data.LinkData;
import data.UserData;

public class DeleteCategoryServlet extends HttpServlet{
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		
		String path = ((HttpServletRequest) request).getRequestURI();
		long categoryId = 0;
		try {
			categoryId = Long.parseLong(URLDecoder.decode(path.toLowerCase().replaceAll("/delete-category/", ""),"UTF-8"));
		} catch (Exception e) {
			response.sendRedirect("/home");
		}
		
		CategoryData cData = new CategoryData();
		LinkData linkData = new LinkData();
		CategoryModel category = cData.getCategory(categoryId);
		
		response.setContentType("text/html");
		if (cData.hasChildren(categoryId) || linkData.hasLinkInDirectory(categoryId)) {
			response.getWriter().println("This category (" + categoryId + ") has contain children category or link. Please delete all or move to other category before delete this category!");
		} else {
			cData.delete(category);
			response.getWriter().println("Delete success category " + category.getName() + "(" + categoryId + ") .");
		}
		
		response.getWriter().println("Go to <a href=\"/view-category\" >Category </a>");
	}
}
